# !/usr/bin/env python
# -*-coding:utf-8 -*-

"""
# Author     ：skyTree
# version    ：python 3.11
# Description：用户序列化器
"""
import re
from rest_framework.relations import PrimaryKeyRelatedField
from rest_framework.serializers import ModelSerializer
from rest_framework import serializers
from users.models import UserProfile
from roles.models import Role


class UserProfileSerializer(ModelSerializer):
    username = serializers.CharField()
    password = serializers.CharField(write_only=True)
    confirm_password = serializers.CharField(write_only=True)
    nick_name = serializers.CharField(required=False, allow_null=True, allow_blank=True)
    mobile = serializers.CharField(required=False, allow_null=True, allow_blank=True)
    email = serializers.CharField(required=False, allow_null=True, allow_blank=True)
    roleId = serializers.IntegerField(write_only=True)
    roles_list = serializers.ListField(read_only=True)

    class Meta:
        model = UserProfile
        fields = ["id", "username", "password", "confirm_password", "nick_name", "mobile", "email", "roleId",
                  "roles_list"]

    def validate(self, attrs):
        password = attrs.get("password")
        confirm_password = attrs.get("confirm_password")
        if password != confirm_password:
            raise serializers.ValidationError("两次密码不一致")
        mobile = attrs.get("mobile", None)
        if mobile and not re.match(r"^1[3-9]\d{9}$", mobile):
            raise serializers.ValidationError("手机号格式不正确")
        email = attrs.get("email", None)
        if email and not re.match(r"", email):
            raise serializers.ValidationError("邮箱格式不正确")
        return attrs

    def create(self, validated_data):
        confirm_password = validated_data.pop("confirm_password")
        password = validated_data.pop("password")
        roleId = validated_data.pop("roleId")
        if not Role.objects.get(id=roleId):
            raise serializers.ValidationError("该角色不存在！")
        user = UserProfile.objects.create_user(**validated_data)
        user.set_password(password)
        user.roles.add(roleId)
        user.save()
        return user


class UserProfileUpdateSerializer(ModelSerializer):
    nick_name = serializers.CharField(required=False, allow_null=True, allow_blank=True)
    mobile = serializers.CharField(required=False, allow_null=True, allow_blank=True)
    email = serializers.CharField(required=False, allow_null=True, allow_blank=True)
    roleId = serializers.IntegerField(write_only=True)
    roles_list = serializers.ListField(read_only=True)

    class Meta:
        model = UserProfile
        fields = ["id", "nick_name", "mobile", "email", "roleId", "roles_list"]

    def update(self, instance, validated_data):
        roleId = validated_data.get("roleId", None)
        if not Role.objects.filter(id=roleId).exists():
            raise serializers.ValidationError("该角色不存在！")
        instance.roles.add(roleId)
        # 假设fields是一个包含需要更新字段名称的列表
        fields = ["nick_name", "email", "mobile"]
        for field in fields:
            setattr(instance, field, validated_data.get(field, getattr(instance, field)))
        # 纯手动操作
        # instance.nick_name = validated_data.get("nick_name", instance.nick_name)
        # instance.email = validated_data.get("email", instance.email)
        # instance.mobile = validated_data.get("mobile", instance.mobile)
        instance.save()
        return instance


class UserProfileDetailSerializer(ModelSerializer):
    get_all_permissions = serializers.CharField(read_only=True)

    class Meta:
        model = UserProfile
        fields = ["id", "username", "nick_name", "mobile", "email", "roles_list", "get_all_permissions"]
